/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controls;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.event.ActionEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import others.Console;
import table.Backup;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import others.Login;
import others.User;
import servlets.BackupsXML;

/**
 *
 * @author Dingo
 */
@ManagedBean
@RequestScoped
public class BackupControl {

    private String name = null;
    private List<Backup> list = null;
    private Backup selectedElement = null;
    @ManagedProperty(value = "#{login}")
    private Login login;

    /** Creates a new instance of BackupControl */
    public BackupControl() {
        list = new ArrayList<Backup>();
        doList();
        /*HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession session = req.getSession();
        Login l = (Login) session.getAttribute("login");
        System.out.println(l.getUser().getLogin());*/
    }

    private void doList() {
        String resp = Console.request("c:\\Windows\\System32\\inetsrv\\appcmd list BACKUPS /xml");
        // creating javaDom parser
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(BackupsXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        Document document = null;
        try {
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(resp));
            document = builder.parse(is);
        } catch (IOException ex) {
            Logger.getLogger(BackupControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(BackupsXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (document != null) {
            Element rootElement = document.getDocumentElement();
            NodeList nodes = rootElement.getChildNodes();

            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (node instanceof Element) {
                    //a child element to process
                    Element child = (Element) node;
                    list.add(new Backup(child.getAttribute("BACKUP.NAME"),
                            child.getAttribute("path")));
                }
            }
        }
    }

    public void add(ActionEvent actionEvent) {
        if (login.userPermited(User.PERM_ADMIN)) {
            String query = "c:\\Windows\\System32\\inetsrv\\appcmd add backup";
            if (name != null && !name.isEmpty()) {
                query += " \"" + name + "\"";
            }
            String log = Console.request(query);
            FacesMessage msg = null;

            Pattern addedp = Pattern.compile("added");
            Matcher addedm = addedp.matcher(log);
            Pattern dupp = Pattern.compile("exists");
            Matcher dupm = dupp.matcher(log);
            if (addedm.find()) {
                if (name != null && !name.isEmpty()) {
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Hura!",
                            "Wykonano backup: " + name);
                } else {
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Hura!",
                            "Wykonano backup");
                }
            } else if (dupm.find()) {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                        "Dodawany backup istnieje. Nazwa musi być unikatowa!");
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                        "Spróbuj ponownie. Sprawdź poprawność danych!");
            }

            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }

    public void remove(ActionEvent actionEvent) {
        if (login.userPermited(User.PERM_ADMIN)) {
            FacesMessage msg = null;
            if (selectedElement != null) {
                String query = "c:\\Windows\\System32\\inetsrv\\appcmd delete backup \""
                        + selectedElement.getName() + "\"";
                String log = Console.request(query);

                Pattern p = Pattern.compile("deleted");
                Matcher m = p.matcher(log);
                if (m.find()) {
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Hura!",
                            "Usunięto backup: " + selectedElement.getName());
                    list.remove(selectedElement);
                } else {
                    msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                            "Prawdopodobnie wskazany backup nie istnieje!");
                }
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                        "Nie wybrano wiersza w tabeli!");
            }

            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }

    public void restore(ActionEvent actionEvent) {
        if (login.userPermited(User.PERM_ADMIN)) {
            FacesMessage msg = null;
            if (selectedElement != null) {
                String query = "c:\\Windows\\System32\\inetsrv\\appcmd restore backup \""
                        + selectedElement.getName() + "\"";
                String log = Console.request(query);

                Pattern p = Pattern.compile("Restored");
                Matcher m = p.matcher(log);
                if (m.find()) {
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Hura!",
                            "Przywrócono backup: " + selectedElement.getName());
                    list.remove(selectedElement);
                } else {
                    msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                            "Prawdopodobnie wskazany backup nie istnieje!");
                }
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                        "Nie wybrano wiersza w tabeli!");
            }
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Backup> getList() {
        return list;
    }

    public void setList(List<Backup> list) {
        this.list = list;
    }

    public Backup getSelectedElement() {
        return selectedElement;
    }

    public void setSelectedElement(Backup selectedElement) {
        this.selectedElement = selectedElement;
    }

    public Login getLogin() {
        return login;
    }

    public void setLogin(Login login) {
        this.login = login;
    }
}